package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.http.MapTool;
import com.recharge.core.entity.ReportOrderGoodsStatisEntity;
import com.recharge.core.mapper.ReportOrderGoodsStatisMapper;
import com.recharge.domain.query.ReportOrderGoodsStatisQueryDO;
import com.recharge.domain.vo.ReportOrderGoodsStatisDO;
import com.recharge.service.ReportOrderGoodsStatisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Collectors;

@Service
public class ReportOrderGoodsStatisServiceImpl extends ServiceImpl<ReportOrderGoodsStatisMapper, ReportOrderGoodsStatisEntity> implements ReportOrderGoodsStatisService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private ReportOrderGoodsStatisMapper reportOrderMapper;

    @Override
    public ResultDO add(ReportOrderGoodsStatisDO domain) {
        return null;
    }

    @Override
    public ResultDO addForList(List<ReportOrderGoodsStatisEntity> dolist) {
       try {
           if(dolist!=null&&dolist.size()>0){
               this.saveBatch(dolist);
           }
       }catch (Exception e){
           e.printStackTrace();
           logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
       }
        return null;
    }

    @Override
    public ResultDO edit(ReportOrderGoodsStatisDO domain) {
        return null;
    }

    @Override
    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        ReportOrderGoodsStatisEntity entity = null;
        try {
            entity = this.getById(id);
        }catch (Exception e){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        ReportOrderGoodsStatisDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    public ResultDO find(ReportOrderGoodsStatisQueryDO query) {
        return null;
    }

    public ResultDO taskReport() {

//        logger.debug( " 当前线程名称：" + Thread.currentThread().getName());

        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i=0;i<30;i++){
            try {
            calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)-1);
            Date nowDa = sdf.parse(calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DATE));
            QueryWrapper<ReportOrderGoodsStatisEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(ReportOrderGoodsStatisEntity::getDayDate,nowDa);
                Integer count = baseMapper.selectCount(wrapper);
                if(count==null||(count!=null&&count==0)){
                    taskReportByDate(nowDa);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    private void taskReportByDate(Date nowDa){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(nowDa.getTime()), ZoneId.systemDefault());
        LocalDateTime startTime = localDateTime.with(LocalTime.MIN);
        LocalDateTime entTime = localDateTime.with(LocalTime.MAX);
        Date todayStartDa = Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant());
        Date todayEndDa = Date.from(entTime.atZone(ZoneId.systemDefault()).toInstant());

        Map<String,Object> param = new HashMap<>();
//        String start = sdf.format(todayStartDa);
//        String end = sdf.format(todayEndDa);
        param.put("beginDate",todayStartDa);
        param.put("endDate",todayEndDa);
        System.out.println("统计订货单,统计订货单时间范围："+todayStartDa+"到"+todayEndDa);
        try {
            List<Map<String,Object>> totalmap = reportOrderMapper.taskReportTodayTotal(param);
            Integer total = ((Long)totalmap.get(0).get("total")).intValue();
            System.out.println(todayStartDa+"到"+todayEndDa+"总数："+total);
            Integer count = total%10000==0?total/10000:(total/10000)+1;

            for(int index=0;index<count;index++){
//               System.out.println(index*10000+"=========beginIndex");
//               System.out.println(10000+"============endIndex");
                param.put("beginIndex",index*10000);
                param.put("endIndex",10000);
                List<ReportOrderGoodsStatisEntity> list = reportOrderMapper.taskReport(param);
                list=list.stream().map(m->{
                    m.setDayDate(nowDa);
                  return m;
                }).collect(Collectors.toList());
                addForList(list);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
        }
    }

    @Override
    public ResultDO reportOrder(ReportOrderGoodsStatisQueryDO query) {
        ResultDO result = new ResultSupport();
        Page<Map<String,String>> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<Map<String,Object>> iPage =null;

        Map<String,Object> param = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(query.getStartTime() != null){
                param.put("beginDate",sdf.parse(query.getStartTime()));
            }
            if(query.getEndTime() != null){
                param.put("endDate",sdf.parse(query.getEndTime()));
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if(query.getTime() != null){
            param.put("dayDate",query.getTime());
        }
        if(query.getType()!=null && !query.getType().equals("")){
            if(query.getType().equals("goodsGroup")){
                param.put("type","goods_group_id");
            }
            if(query.getType().equals("goods")){
                param.put("type","goods_id");
            }
            if(query.getType().equals("merchant")){
                param.put("type","merchant_id");
            }
            if(query.getType().equals("businessType")){
                param.put("type","business_type");
            }
            if(query.getType().equals("provinceCode")){
                param.put("type","province_code");
            }
            if(query.getType().equals("regionCode")){
                param.put("type","region_code");
            }
        }

        if(query.getOrder() != null){
            param.put("order",query.getOrder());
        }
        if(query.getSortField() != null){
            if(query.getSortField().equals("successNumber")||query.getSortField().equals("failNumber")||query.getSortField().equals("processNumber")||query.getSortField().equals("unconfirmedNumber")||
               query.getSortField().equals("totalNumber")||query.getSortField().equals("successRate")||query.getSortField().equals("denomination")||query.getSortField().equals("amount")||
               query.getSortField().equals("cost")||query.getSortField().equals("profit")||query.getSortField().equals("successRateThree")||query.getSortField().equals("successRateTen")||
               query.getSortField().equals("successRateThirty")||query.getSortField().equals("title")
            ){
                param.put("sortField",query.getSortField());
            }

        }


        //10-20添加更多筛选
        if(query.getMerchantId()!=null && !query.getMerchantId().equals("")){
            param.put("merchantId",query.getMerchantId());
        }
        if(query.getProvinceCode()!=null && !query.getProvinceCode().equals("")){
            param.put("provinceCode",query.getProvinceCode());
        }
        if(query.getGroupType()!=null && !query.getGroupType().equals("")){
            param.put("groupType",query.getGroupType());
        }
        if(query.getBusinessClass()!=null && !query.getBusinessClass().equals("")){
            param.put("businessClass",query.getBusinessClass());
        }
        if(query.getServiceProvider()!=null && !query.getServiceProvider().equals("")){
            param.put("serviceProvider",query.getServiceProvider());
        }
        if(query.getDenomination()!=null){
            param.put("denomination",query.getDenomination());
        }
        if(query.getStatus()!=null &&!query.getStatus().equals("")){
            param.put("status",query.getStatus());
        }

        try {
            if(query.getStartTime() != null){
                Date queryStatrtDa = sdf.parse(query.getStartTime());
                Date queryEndDa = sdf.parse(query.getEndTime());
                Date nowDa = new Date();
                LocalDateTime localDateTime  = LocalDateTime.ofInstant(Instant.ofEpochMilli(nowDa.getTime()), ZoneId.systemDefault());
                LocalDateTime startTime = localDateTime.with(LocalTime.MIN);
                LocalDateTime entTime = localDateTime.with(LocalTime.MAX);
                Date todayStartDa = Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant());
                Date todayEndDa = Date.from(entTime.atZone(ZoneId.systemDefault()).toInstant());
                if(
                        (queryStatrtDa.compareTo(todayEndDa)==-1 || queryStatrtDa.compareTo(todayEndDa)==0)&&(todayStartDa.compareTo(queryEndDa)==-1||(todayStartDa.compareTo(queryEndDa)==0))
                ){

                    iPage = reportOrderMapper.taskReportForToDay(page,param);
                }else{
                    iPage = reportOrderMapper.reportOrderList(page,param);
                }
            }else{
                iPage = reportOrderMapper.reportOrderList(page,param);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<ReportOrderGoodsStatisDO> doList = null;
        if(iPage.getRecords()!=null&&iPage.getRecords().size()>0){
            try {
                doList = iPage.getRecords().stream().map(m->{
                    if(m.get("successRate")==null){
                        m.put("successRate",0);
                        if(m.get("totalNumber")!=null&&m.get("successNumber")!=null){
                            Double sucess = Double.valueOf(m.get("successNumber").toString());
                            Double total = Double.valueOf(m.get("totalNumber").toString());
                            if(total!=0){
                                Double succesrate = sucess/total;
                                m.put("successRate",succesrate);
                            }
                        }

                    }
                    if(m.get("profit")==null){
                        m.put("profit",0);
                        if(m.get("amount")!=null&&m.get("cost")!=null){
                            Double amount = Double.valueOf(m.get("amount").toString());
                            Double cost = Double.valueOf(m.get("cost").toString());
                            Double profit = amount-cost;
                            m.put("profit",profit);
                        }
                    }
                    if(m.get("denomination")==null){
                        m.put("denomination",0);
                    }
                    ReportOrderGoodsStatisDO orderGoodsStatisDO = MapTool.map2Bean(m,ReportOrderGoodsStatisDO.class,true);

                    return orderGoodsStatisDO;
                }).collect(Collectors.toList());
            }catch (Exception e){
                e.printStackTrace();
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }
        }
        PageDO<ReportOrderGoodsStatisDO> pageDO = new PageDO<>();


        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);


        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);

        return result;
    }

    @Override
    public ResultDO reportOrderByDayDate(ReportOrderGoodsStatisQueryDO query) {
        ResultDO result = new ResultSupport();
        Page<Map<String,String>> page = new Page<>(1,40);
        IPage<Map<String,Object>> iPage =null;

        Map<String,Object> param = new HashMap<>();
        if(query.getMerchantId() != null){
            param.put("merchantId",query.getMerchantId());
        }
        if(query.getProvinceCode() != null){
            param.put("provinceCode",query.getProvinceCode());
        }
        if(query.getGroupType() != null){
            param.put("groupType",query.getGroupType());
        }
        if(query.getBusinessClass() != null){
            param.put("businessClass",query.getBusinessClass());
        }
        if(query.getDateType() != null){
            param.put("DateType",query.getDateType());
        }
        if(query.getTime() != null){
            param.put("dayDate",query.getTime());
        }
        //10-20新增筛选
        if(query.getServiceProvider()!=null && !query.getServiceProvider().equals("")){
            param.put("serviceProvider",query.getServiceProvider());
        }
        if(query.getStatus()!=null &&!query.getStatus().equals("")){
            param.put("status",query.getStatus());
        }

        try {
            iPage = reportOrderMapper.reportOrderByDayDate(page,param);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<ReportOrderGoodsStatisDO> doList = null;
        if(iPage.getRecords()!=null&&iPage.getRecords().size()>0){
            try {
                doList = iPage.getRecords().stream().map(m->{
                    ReportOrderGoodsStatisDO orderGoodsStatisDO = MapTool.map2Bean(m,ReportOrderGoodsStatisDO.class,true);
                    return orderGoodsStatisDO;
                }).collect(Collectors.toList());
            }catch (Exception e){
                e.printStackTrace();
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }



        }
        PageDO<ReportOrderGoodsStatisDO> pageDO = new PageDO<>();


//        pageDO.setCurrentPage(iPage.getCurrent());
//        pageDO.setPageCount(iPage.getPages());
//        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);


        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);

        return result;
    }


    private ReportOrderGoodsStatisDO getDomain(ReportOrderGoodsStatisEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        ReportOrderGoodsStatisDO domain = new ReportOrderGoodsStatisDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<ReportOrderGoodsStatisDO> getDomainList(List<ReportOrderGoodsStatisEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<ReportOrderGoodsStatisDO> doList = new ArrayList<ReportOrderGoodsStatisDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(ReportOrderGoodsStatisEntity entity : list) {

                ReportOrderGoodsStatisDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
